package com.ruoyi.lession.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.lession.common.ResultInfo;
import com.ruoyi.lession.config.AlipayConfig;
import com.ruoyi.lession.entily.*;
import com.ruoyi.lession.mapper.*;
import com.ruoyi.lession.service.QuestService;
import com.ruoyi.lession.utils.AliUtils;
import com.ruoyi.lession.utils.JwtTokenUtils;
import com.ruoyi.model.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class QuestServiceImpl implements QuestService {
    @Value("${alpay.appid}")
    public String appid;

    @Value("${alpay.url}")
    public String url;

    @Value("${alpay.privatekey}")
    public String private_key;

    @Value("${alpay.alipaypublickey}")
    public String alipay_public_key;

    @Resource
    QuestMapper questMapper;

    @Resource
    TitleMapper titleMapper;
    @Resource
    QuestTitleMapper questTitleMapper;

    @Resource
    TitleContentMapper titleContentMapper;
    @Resource
    LessonMapper lessonMapper;

    @Resource
    OrderMapper orderMapper;
    @Override
    public ResultInfo findByQuestList(Integer pageNum, Integer pageSize) {
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        //查询列表数据
        QueryWrapper<Quest> queryWrapper = new QueryWrapper<>();
        List<Quest> list = questMapper.selectList(queryWrapper);
        //将集合放入分页
        PageInfo<Quest>  page= new PageInfo<>(list);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",page.getTotal());
        return new ResultInfo(true,200,"查询并分页成功",map);
    }

    @Override
    public ResultInfo insert(Quest quest) {
        //生成时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
        String format1 = format.format(date);
        quest.setCreattime(format1);
        //将自动生成的时间添加到数据中
        questMapper.insert(quest);
        return new ResultInfo(true,200,"数据添加成功",null);
    }

    @Override
    public ResultInfo QuestUpdateStutas(Quest quest) {
        //修改状态
        questMapper.updateById(quest);
        return new ResultInfo(true,200,"问卷已结束",null);
    }

    @Override
    public List<Title> findByTitleList() {
        QueryWrapper<Title> queryWrapper = new QueryWrapper<>();
        List<Title> titles = titleMapper.selectList(queryWrapper);
        return titles;
    }

    @Override
    public void save(QuestionnaireAddUtil questionnaireAddUtil) {
        //生成时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
        String format1 = format.format(date);
        questionnaireAddUtil.setCreattime(format1);
        questMapper.insert(questionnaireAddUtil);
    }

    @Override
    public void saveBatch(List<QuestTitle> questionnaireTopics) {
        for (int i = 0; i <questionnaireTopics.size() ; i++) {
            questionnaireTopics.get(i);
            questTitleMapper.insert(questionnaireTopics.get(i));
        }
    }

    @Override
    public ResultInfo deleteId(Long id) {
        QueryWrapper<Quest> questionnaireWrapper = new QueryWrapper<>();
        questionnaireWrapper.eq("id",id);
        questMapper.delete(questionnaireWrapper);
        QueryWrapper<QuestTitle> questionnaireTopicQueryWrapper = new QueryWrapper<>();
        questionnaireTopicQueryWrapper.eq("id",id);
        questTitleMapper.delete(questionnaireTopicQueryWrapper);
        return new ResultInfo(true,200,"问卷删除成功",null);
    }

    @Override
    public List<TitleContentUtil> topicUtilList(Long id) {
        List<TitleContentUtil> list = titleContentMapper.select(id);
        return list;
    }

    @Override
    public ResultInfo sumcum(List<ContentSum> contentSumList) {
        List<String> listContent = new ArrayList<>();
        Integer listBlanks = 0;
        for (int i = 0; i < contentSumList.size(); i++) {
            ContentSum contentSum = contentSumList.get(i);
            List<TitleContent> cidList = contentSum.getContentsList();
            if (contentSum.getType()!="填空"){
                for (int j = 0; j < cidList.size(); j++) {
                    listContent.add(cidList.get(j).getCid()+"");
                }
            }
        }

        Integer contentCnum = titleContentMapper.cnumSum(listContent);
        contentCnum = contentCnum + listBlanks;
        return new ResultInfo(true,200,"查询成功",contentCnum);
    }

    @Override
    public ResultInfo repoetList(Integer cnum) {
        List<Report> reports = titleContentMapper.reportList(cnum);
        return new ResultInfo(true,200,"报告查询成功",reports);
    }

    @Override
    public ResultInfo findByLessonReportList(Long rid) {
        //查询课程
        List<Lesson> lessons = titleContentMapper.lessonList(rid);
        //查询视频
        List<Video> videos = titleContentMapper.videoList(rid);
        Map<String,Object> map = new HashMap<>();
        map.put("lessons",lessons);
        map.put("videos",videos);
        System.out.println(map);
        return new ResultInfo(true,200,"查询成功",map);
    }

    @Transient
    @Override
    public Integer orderFromInsert(Order order, HttpServletRequest request) {
        QueryWrapper<Lesson> wrapper = new QueryWrapper<>();
        wrapper.eq("id",order.getId());
        List<Lesson> list = lessonMapper.selectList(wrapper);
        Lesson lesson = list.get(0);
        String token = request.getHeader("token");
        Claims zxj = JwtUtils.getJwt_Body(token).setId(token);
        Integer uid = (Integer) zxj.get("userid");
        order.setUid(uid);
        order.setPrice(lesson.getPrice());
        order.setStatus("未付款");
        Integer save = orderMapper.insert(order);
        if (save>0){
            return order.getOid();
        }
        return 0;
    }

    @Override
    public void Alipay(Integer oid, HttpServletResponse servletResponse) {
        //查询订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid",oid);
        List<Order> list = orderMapper.selectList(queryWrapper);
        Order order = list.get(0);
        //为订单添加支付状态
        order.setPayment("支付宝支付");
        //生成订单号
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String seconds = new SimpleDateFormat("HHmmss").format(new Date());
        int randomOne = (int) (Math.random()*100);
        int randomTwo = (int) (Math.random()*100);
        if (randomOne<10){
            randomOne = randomOne + 10;
        }
        if (randomTwo<10){
            randomTwo = randomTwo + 10;
        }
//        date+"00001000"+randomOne+"00"+seconds+randomTwo;
        String sOfnum = date + "00001000" + randomOne + "00" + seconds + randomTwo;
        order.setOrderid(sOfnum);
        orderMapper.update(order,queryWrapper);
        //支付
        AlipayClient alipayClient = new DefaultAlipayClient(url,appid,private_key,"json", "UTF-8",alipay_public_key,"RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl("http://www.dzh.com/es/aliNotify");
        request.setReturnUrl("http://www.dzh.com/apliay/success.html");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", sOfnum);
        bizContent.put("total_amount", order.getPrice());
        bizContent.put("subject", "商品");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
//            String body = response.getBody();
            String form= "" ;
            try  {
                form = alipayClient.pageExecute(request).getBody();  //调用SDK生成表单
            }  catch  (Exception e) {
                e.printStackTrace();
            }

            try {
                servletResponse.setContentType( "text/html;charset="  + "UTF-8");
                servletResponse.getWriter().write(form); //直接将完整的表单html输出到页面
//                servletResponse.getWriter().flush();
//                servletResponse.getWriter().close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            System.out.println("调用失败");
        }
    }

    @Override
    public String aliNotify(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> paramsMap = AliUtils.getReceiveMap(request); //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            String out_trade_no = paramsMap.get("out_trade_no");
            String total_amount = paramsMap.get("total_amount");
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("ofnum",out_trade_no);
            List<Order> list = orderMapper.selectList(wrapper);
            if (list.size()<=0){
                return "failure";
            }
            Order order = list.get(0);
            if (!order.getPrice().equals(total_amount)){
                return "failure";
            }
            order.setStatus("支付完成");
            orderMapper.update(order,wrapper);
            return "success";
        }
        // TODO 验签失败则记录异常日志，并在response中返回failure.
        return "faliure";
    }

    @Override
    public String payList(String outtradeno) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.UNIFIEDORDER_URL,appid,private_key,"json","UTF-8",AlipayConfig.ALIPAY_PUBLIC_KEY,"RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outtradeno);
        //20150320010101001
        //bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            String body = response.getBody();
            Map map = JSON.parseObject(body, Map.class);
            Map alipay_trade_query_response = (Map) map.get("alipay_trade_query_response");
            String code = (String) alipay_trade_query_response.get("code");
            if (!code.equals("10000")){
                System.out.println("订单未支付");
                return "订单未支付";
            }
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("orderid",outtradeno);
            List<Order> list = orderMapper.selectList(wrapper);
            Order order = list.get(0);
            order.setStatus("已支付");
            orderMapper.update(order,wrapper);
            return "订单已支付，订单状态已修改";
        } else {
            System.out.println("调用失败");
            return "订单未支付";
        }
    }

    @Override
    public List<Quest> findQuestListByIds(Long ids) {
        QueryWrapper<Quest> queryWrapper = new QueryWrapper<>();
        return questMapper.selectList(queryWrapper);
    }

    @Override
    public List<TitleContent> findTitleCotentListByIds(Long ids) {
        QueryWrapper<TitleContent> queryWrapper = new QueryWrapper<>();
        return titleContentMapper.selectList(queryWrapper);
    }

    @Override
    public void savePoi(List<Quest> quests) {
        questMapper.insert((Quest) quests);
    }

}
